//
//  XGLoadingPictureProgressCell.swift
//  TodayNews
//
//  Created by monkey on 2020/2/27.
//  Copyright © 2020 itcast. All rights reserved.
//

import JXPhotoBrowser
import Photos
import MBProgressHUD

// MARK: - XGLoadingPictureProgressCell

class XGLoadingPictureProgressCell: JXPhotoBrowserImageCell
{
    /// 加载图片
    /// - Parameters:
    ///   - url: 图片url
    ///   - placeholderImage: 占位图片
    func reloadImage(url: String, placeholderImage: UIImage? = nil) -> Void
    {
        imageView.kf.setImage(with: URL(string: url), placeholder: placeholderImage, progressBlock: { [weak self] (received, total) in
            self?.progressView.progress = CGFloat(received) / CGFloat(total)
        }) { [weak self] (result) in
            switch result {
            case .success(_):
                self?.progressView.progress = 1.0
            case .failure(_):
                self?.progressView.progress = 0.0
            }
            
            self?.setNeedsLayout() // 加载完图片后调用 刷新布局
        }
    }
    
    override func setup()
    {
        super.setup()
        addSubview(progressView)
        // 长按事件
        longPressedAction = { (cell, _) in
            let alertSheet = UIAlertController(title: "提示", message: nil, preferredStyle: .actionSheet)
            alertSheet.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
            alertSheet.addAction(UIAlertAction(title: "保存到相册", style: .default, handler: { (_) in
                guard let image = cell.imageView.image,
                    let appName = Bundle.main.appName else {
                    return
                }
                
                // 保存到相册
                PHPhotoLibrary.saveImage(image: image, collectionName: appName) { (result) in
                    switch result {
                    case .success(let str):
                        MBProgressHUD.showSuccessTips(text: str)
                    case .failure(let str):
                        MBProgressHUD.showErrorTips(text: str)
                    }
                }
            }))
            
            cell.photoBrowser?.present(alertSheet, animated: true, completion: nil)
        }
    }
    
    override func layoutSubviews()
    {
        super.layoutSubviews()
        progressView.center = CGPoint(x: bounds.width * 0.5, y: bounds.height * 0.5)
    }
    /// 进度视图
    private lazy var progressView = XGPhotoBrowserProgressView(frame: CGRect(x: 0, y: 0, width: kPicturesViewItemWidth, height: kPicturesViewItemWidth))
}

// MARK: - XGPhotoBrowserProgressView

private class XGPhotoBrowserProgressView: UIView
{
    /// 进度
    var progress: CGFloat = 0 {
        didSet {
            DispatchQueue.main.async {
                self.fanshapedLayer.path = self.makeProgressPath(self.progress).cgPath
                self.isHidden = self.progress >= 1.0 || self.progress < 0.01
            }
        }
    }
    
    public override init(frame: CGRect)
    {
        super.init(frame: frame)
        if self.frame.size.equalTo(.zero) {
            self.frame.size = CGSize(width: 50, height: 50)
        }
        
        backgroundColor = UIColor.clear
        let strokeColor = UIColor(white: 1, alpha: 0.4).cgColor
        fanshapedLayer = CAShapeLayer()
        fanshapedLayer.fillColor = strokeColor
        layer.addSublayer(fanshapedLayer)
    }
    
    public required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 扇形路径
    private var fanshapedLayer: CAShapeLayer!
    /// 绘制圆弧路径
    private func makeProgressPath(_ progress: CGFloat) -> UIBezierPath
    {
        let center = CGPoint(x: bounds.midX, y: bounds.midY)
        let radius = min(center.x, center.y)
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: -CGFloat.pi / 2, endAngle: -CGFloat.pi / 2 + CGFloat.pi * 2 * progress, clockwise: true)
        path.addLine(to: center)
        path.close()
        path.lineWidth = 1
        return path
    }
}
